package com.xingfei.blog.controller.validate;

import com.xingfei.blog.constants.RedisConstants;
import com.xingfei.blog.redisCluster.RedisClusterUtil;
import com.xingfei.blog.service.WebUserService;
import com.xingfei.blog.utils.RedisUtil;
import com.xingfei.blog.utils.TokenCodeUtil;
import com.xingfei.blog.vo.TokenCode;
import com.xingfei.blog.vo.UserVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.text.MessageFormat;

/**
 * Created with IntelliJ IDEA.
 *
 * @author: chenxingfei
 * @time: 2017/3/22  18:43
 * To change this template use File | Settings | File Templates.
 */
@Controller
@RequestMapping("active")
public class ActiveController {

    @Autowired
    private WebUserService webUserService;

    @Autowired
    private RedisClusterUtil redisCluster;

    /**
     * 用户邮件激活
     *
     * @param ak
     * @return
     */
    @GetMapping(value = "/emailActive")
    public ModelAndView emailActive(String ak) {
        //激活成功跳转至第三步
        ModelAndView modelAndView = new ModelAndView("/activesure");
        //解密
        if (StringUtils.isNotBlank(ak)) {
            TokenCode tokenCode = TokenCodeUtil.getTokenCode(ak);
            if (tokenCode != null) {
                Integer integer = dealUserActiveInfo(tokenCode);
                if (integer > 0) {
                    modelAndView = new ModelAndView("/register/jianyi-register-email4");
                    modelAndView.addObject("tk_u", ak);
                    return modelAndView;
                }
            }
        } else {
            modelAndView.addObject("activeResult", "邮箱验证失败!");
            modelAndView.addObject("activeMsg", "验证新邮箱失败，验证码错误或链接超出有效期。请点击再次发送验证邮件。您也可以修改邮箱后重新发送验证邮件！");
        }
        return modelAndView;
    }

    /**
     * 处理用户激活信息
     *
     * @param tokenCode
     */
    private Integer dealUserActiveInfo(TokenCode tokenCode) {
        Integer result = 0;
        String userId = tokenCode.getUserId();
        if (StringUtils.isNotBlank(userId)) {
            String key = MessageFormat.format(RedisConstants.USER_TOKEN_CODE_KEY, userId);
            //String userInfo = RedisUtil.get(key, 1);
            String userInfo = redisCluster.get(key);
            if (StringUtils.isNotBlank(userInfo) && StringUtils.contains(userInfo, ":")) {
                String[] userINfo = userInfo.split(":");
                UserVO userVo = new UserVO();
                userVo.setId(Long.parseLong(userINfo[0]));
                userVo.setEmail(userINfo[1]);
                result = this.webUserService.updateUserAndUserInfo(userVo);
            }
        }
        return result;
    }
}
